<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意:只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"> </el-alert>
      <div class="attr">
        <span>选择商品分类： </span>
        <el-cascader v-model="selectedKeys" :options="categoriesList" :props="cateProps" @change="handleChange" clearable></el-cascader>
      </div>
      <!-- tab -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮 -->
          <el-button type="primary" size="mini" :disabled="btnDisabled" @click="showAddDialog">添加参数</el-button>

          <!-- 表单 -->
          <el-table :data="paramsData" style="width: 100%" border stripe>
            <el-table-column type="expand" label="明细" width="width"> </el-table-column>
            <el-table-column type="index" label="序号" width="width"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="width"> </el-table-column>
            <el-table-column label="操作" width="width">
              <template slot-scope="scope">
                 <el-button type="primary" class="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                 <el-button type="danger" class="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- <el-tab-pane label="静态属性" name="only"></el-tab-pane> -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 按钮 -->
          <el-button type="primary" size="mini" :disabled="btnDisabled" @click="showAddDialog">添加属性</el-button>

          <!-- 表单 -->
          <el-table :data="paramsData" style="width: 100%" border stripe>
            <el-table-column type="expand" label="明细" width="width"> </el-table-column>
            <el-table-column type="index" label="序号" width="width"> </el-table-column>
            <el-table-column prop="attr_name" label="属性名称" width="width"> </el-table-column>
            <el-table-column label="操作" width="width">
              <template slot-scope="scope">
                 <el-button type="primary" class="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
              <el-button type="danger" class="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加对话框 -->
    <el-dialog :title="'添加'+title" :visible.sync="addFormDialogVisible" width="width" @close="addFormDialogClosed">
      <el-form :model="addForm" :rules='addFormRules' ref="addFormRef">
        <el-form-item :label="title" label-width="100px" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addFormDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog :title="'修改'+title" :visible.sync="editFormDialogVisible" width="width" @close="editFormDialogClosed">
      <el-form :model="editForm" :rules='editFormRules' ref="addFormRef">
        <el-form-item :label="title" label-width="100px" prop="attr_name">
          <el-input v-model="editForm.attr_name" clearable=""></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editFormDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      //分类列表
      categoriesList: [],
      attributesList: [],
      //级联选择器的属性配置
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        expandTrigger: "hover",
      },
      //级联选择器选中的id数组
      selectedKeys: [],
      activeName: "many",
      
      // 分类参数
      paramsData: [],
      // 显示与隐藏对话框
      addFormDialogVisible:false,
      //添加表单
      addForm:{
        attr_name:''
      },
      addFormRules:{
        attr_name:[{required: true, message:'请输入参数名称', trigger: 'blur'}]
      },

      // 修改对话框
      editFormDialogVisible:false,
      //添加表单
      editForm:{
        attr_name:''
      },
      editFormRules:{
        attr_name:[{required: true, message:'请输入参数名称', trigger: 'blur'}]
      },

      
      
 


    };
  },
  created() {
    this.getCateGoriesList();
  },
  computed: {
    //当前选中的三级分类的id
    cateId() {
      return this.selectedKeys.length === 3 ? this.selectedKeys[2] : null;
    },
    //是否禁用按钮
    btnDisabled() {
      return this.selectedKeys.length === 3 ? false : true;
    },
    // 标题
    title() {
      return this.activeName === "many" ? "动态参数" : "静态属性";
    },
  },
  methods: {
    async getCateGoriesLists() {
      const { data: res } = await this.$http.get(`categories/${this.attr.cat_id}/attributes`, {
        sel: "many",
      });
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数列表失败");
      }
      //提示获参数限列表成功
      this.$message.success("获取参数列表成功");
      this.attributesList = res.data;
    },
    async getCateGoriesList() {
      const { data: res } = await this.$http.get("categories");
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类列表失败");
      }
      //提示获取分类列表成功
      this.$message.success("获取分类列表成功");
      this.categoriesList = res.data;
    },
    //监听级联选择器的改变事件
    handleChange() {
      this.getParamsData();
    },
    //监听标签页的点击事件
    handleClick() {
      // console.log(this.activeName)
      this.getParamsData();
    },
    //获取参数
    async getParamsData() {
      // 判断是否选中三级分类，如果未选中，则要重新选择
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = [];
        this.paramsData = [];
        return;
      }
      //根据所选分类，获取动态参数或静态属性
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName },
      });
      if (res.meta.status !== 200) {
        this.$message.error("获取属性参数失败");
      }
      console.log(res.data);
      this.paramsData = res.data;
    },

    // 显示对话框
    showAddDialog(){
      this.addFormDialogVisible=true
    },
    //监听对话框关闭
    addFormDialogClosed(){
      this.$refs.addFormRef.resetFields()
    },
    //添加属性参数
    addParams(){
      this.$refs.addFormRef.validate(async valid=>{
        if(!valid){
          return
        }
        const{data:res}=await this.$http.post(`categories/${this.cateId}/attributes`,{
        attr_name:this.addForm.attr_name,
        attr_sel:this.activeName
      })
      console.log(res)
      if(res.meta.status!==201){
       return this.$message.error('添加参数失败')
      }
        
      this.$message.success('添加参数成功')
      this.addFormDialogVisible=false
      this.getParamsData()
      })
      
    },

    // 删除参数
      removeParams(id){
        this.$confirm('确定要删除该参数吗?','提示',{
          confirmButtonText:'确定',
          cancelButtonText:'取消',
          type:'warning'
        }).then(async ()=>{
          const{data:res}=await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
          // console.log(res)
          if(res.meta.status!==200){
           return this.$message.error('删除参数失败')
          }
          //提示删除成功
          this.$message.success('删除参数成功')
          //刷新
          this.getParamsData()
        }).catch(()=>{
          this.$message.info('已取消删除')
        })
      },

    //监听修改对话框关闭
    editFormDialogClosed(){
      this.$refs.addFormRef.resetFields()
    },
    //修改属性参数
    editParams(){
      this.$refs.addFormRef.validate(async valid=>{
        if(!valid){
          return
        }
        const{data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
        attr_name:this.editForm.attr_name,
        attr_sel:this.activeName,
        attr_vals:this.editForm.attr_vals
      })
      console.log(res)
      if(res.meta.status!==200){
       return this.$message.error('更新参数失败')
      }
        
      this.$message.success('更新参数成功')
      this.editFormDialogVisible=false
      this.getParamsData()
      })
      
    },
    // 显示修改对话框
    async showEditDialog(id){
       const{data:res}=await this.$http.get(`categories/${this.cateId}/attributes/${id}`)
          // console.log(res)
          if(res.meta.status!==200){
           return this.$message.error('查询参数失败')
          }
          //提示查询成功
          this.$message.success('查询参数成功')
          this.editForm=res.data
          //刷新
          this.getParamsData()
      this.editFormDialogVisible=true
    }


  },
};
</script>
<style lang="less" scoped>
.attr {
  margin-top: 10px;
}
</style>
